import requests
import execjs
from bs4 import BeautifulSoup
import lxml
from lxml import html  # 添加这行导入语句

import os

def download_song(song_name):
    cookies = {
        'NMTID': '00On0ZFdTb6EIle0Ed2tYYVmRZ5T80AAAGUb_y6-w',
        '_iuqxldmzr_': '32',
        '_ntes_nnid': '8945ef78e9a950d53a15250e89bbe751,1747720182556',
        '_ntes_nuid': '8945ef78e9a950d53a15250e89bbe751',
        'WEVNSM': '1.0.0',
         'WNMCID': 'mhafun.1747720184685.01.0',
        'WM_TID': 'mxhpEjzly3dBAAAVQEaDDNthhmEqzo2G',
        'ntes_utid': 'tid._.V4JHX2Gxe1BFUkFVBVPTTNo0gzSEGKJu._.0',
        'sDeviceId': 'YD-A2RStm2CiR1EU1QFVAeTDNs00jGFXaPf',
        '__snaker__id': '7H5FEjnDmFWe12xB',
        'WM_NI': '5DhNYDEh%2Bi1cWeERvUS0POyvZhmEM7P%2BVWxg9kn6l9RFWf6da3LbSOOxFdFcj2LUdKAydTB9bFwTebfbjf3%2FJOsTyLfVm4USUDae%2FCNpS2FogYhLp%2FL%2BT08QO3t%2FthWRQnc%3D',
        'WM_NIKE': '9ca17ae2e6ffcda170e2e6ee94c83cf2928387e53ef2928eb2d44a878b8b86c641a9b99ed8b868e992fda8b62af0fea7c3b92af79ca8afdc5087b8e58ab46995bb8bb3f55f91f0a0b0fc7e9ab8a3a6d03d94f59ab8fb6dfbb5a2d7ef33929a9987b570a3ed8483d2458da88a85c569aaee84b6e74183a7acb5c133a29ab9b5e86aa6bea687b2258a91bdb5fc48a68aa3d5d859979caf86ae498eb09dd3c565a587a8adf32590f59cd1bb5b8dedbcd0f764958e9f8fe237e2a3',
        'ntes_kaola_ad': '1',
        'gdxidpyhxdE': '35wmhkGiJyl7wKKJ7l28lsGdvlWAaoSvZml8N%2FBqfpB8d%5C840%2B3BtWARJPe%5CLz%2BGQOH7xmN88PkpuMjQDqOYxmBqTEafX24kexfgGJaxwhUE09CnoWJvex6AQr6dmn1%5Cri11sISMiHXEYVJlo%5CXKneSYUOmS84%5C%2B2Sd1mN9g8z4hXTrV%3A1748606840909',
        '__csrf': 'edd1ba51c934c0bf38af7cabda7699d0',
        'MUSIC_U': '000A5C339E6426D0A1A8B884A11367CCAAC6543F0D2E5AEBD561BBC5AD7380A603C249A340A310984CE317AC21CAEDB54AA17ECFAB4FD925C7FFB8701FFCC3695541878A4FE9E5CEE0186DDBE8A86FF5A7449E24C9840E294349A3013E4DECF1D0CD83221C86DD361137AD89D858901D9C1DCB8E63043A7F13C30A034C2C078AA3A3B77D2760007C515D6E4C3B9980ABCA25C99095CA2990F158882BDF805A467B5564834F4DF44D0156D81B1E31489AA64A94E23144BADF3D60CB6B5D6A4B9F9B8F06C608071DE9D7A1CC79C28907342F95AB6C688000A97FA24176E17719AEC621A5136A5705A0050AA3A3C8F44DD3465703D6101F54EA848B44DB110E0C668047727F370B3DE824090396302591F0273011F314BC046C8EE5882A7BD3A14D4000B55E12D28C2012CFD3DB524CDBAF2812580AECEB62DDC0DAD149817084F30FE90C28A187953012AD0E06C771B596047E8A6777BBC6AEAE6D7E03C5AAA312B7',
        'JSESSIONID-WYYY': 'v9POJGYtdDcfGDpBA%2Fp35gyKxuzT9i8Hvb20VGyFYXE9Vm7rso4O28oQVYnApSew74yoy62qY%5CaKVryYj3Iuq8IcfIcjp7hcwKVdUT%2BlQOwkHN2hlwMQGq%5CoeES5PCX4JykSwZ4qVD3HWMJpspxeOuw11YP96hpr%2FZu5ybrrh0TNF5rc%3A1748613975402',
        'playerid': '63466650',
    }

    headers = {
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'no-cache',
        'content-type': 'application/x-www-form-urlencoded',
        'origin': 'https://music.163.com',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://music.163.com/',
        'sec-ch-ua': '"Chromium";v="136", "Microsoft Edge";v="136", "Not.A/Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0',
    }

    params = {
        'csrf_token': 'edd1ba51c934c0bf38af7cabda7699d0',
    }

    # 搜索歌曲获取ID和名称
    search_url = 'https://music.163.com/api/search/get'
    search_params = {
        's': song_name,  # 搜索关键词
        'type': 1,       # 1表示搜索歌曲
        'limit': 10      # 返回结果数量
    }

    search_response = requests.post(
        search_url,
        params=params,
        cookies=cookies,
        headers=headers,
        data=search_params
    )

    # 解析搜索结果
    songs = search_response.json()['result']['songs']
    for song in songs:
        print(f"歌曲ID: {song['id']}, 歌曲名: {song['name']}, 歌手: {song['artists'][0]['name']}")

    if not songs:
        print("未找到相关歌曲")
        return

    first_song_id = songs[0]['id']

    # 获取歌曲下载链接
    i1x = {
        "ids": f"[{first_song_id}]",
        "level": "exhigh",
        "encodeType": "aac",
        "csrf_token": "edd1ba51c934c0bf38af7cabda7699d0"
    }

    res = execjs.compile(open("wyy_jiami.js", encoding='utf-8').read()).call("getKey", i1x)

    data = {
        'params': res['encText'],
        'encSecKey': res['encSecKey'],
    }

    response = requests.post(
        'https://music.163.com/weapi/song/enhance/player/url/v1',
        params=params,
        cookies=cookies,
        headers=headers,
        data=data,
    )

    voice_url = response.json()['data'][0]['url']
    response = requests.get(voice_url, headers=headers)
    # 使用 os.path.join 拼接路径
    file_path = os.path.join("D:", "Picture", "video", "MP3", f"{song_name}.mp3")
    with open(file_path, "wb") as f:
        f.write(response.content)


if __name__ == "__main__":
    song_names = input("请输入歌曲名（多个歌曲名用逗号分隔）：").split(',')
    for song_name in song_names:
        song_name = song_name.strip()
        if song_name:
            download_song(song_name)
    # downlod_toplist_html()